package com.lingyun.common.utils.es;

import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 *
 * elasticsearch 工具类
 *
 */
@Component
public class ElasticSearchUtils {

    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchUtils.class);

    @Resource
    RestHighLevelClient restHighLevelClient;


    /**
     * 判断一个索引是否存在
     * @param indexName  索引名称
     * @return true存在   false没有
     */
    public boolean isExistsIndex(String indexName){
        GetIndexRequest request = new GetIndexRequest(indexName);
        try {
            return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            logger.error("ES索引[{}]存在性检查异常: {}",
                    indexName,                       // 替换第一个{}
                    e.getMessage(),                  // 替换第二个{}
                    e);                              // 异常对象(单独处理)
            return false;
        }
    }

    /**
     *判断一个文档是否存在
     * @param indexName   索引名称
     * @param id          文档id
     * @return true存在   false没有
     */
    public boolean isExistsDocument(String indexName, String id){
        GetRequest getRequest = new GetRequest(indexName,id);
        try {
            return restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            logger.error("ES文档[{}@{}]存在性检查异常: {}",
                    id,
                    indexName,
                    e.getMessage(),
                    e);
            return false;
        }

    }






}
